package com.xdclass.thread.hang;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Author: Timo
 * @Date: 2019/4/26 11:10
 * @Description: 等待
 */
public class WaitDemo implements Runnable{
    private static Object object = new Object();
    private static Object waitObject = new Object();

    @Override
    public void run() {
        synchronized (waitObject) {
            System.out.println(Thread.currentThread().getName()+"占用资源");
            try {
                waitObject.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
        System.out.println(Thread.currentThread().getName()+"释放资源");

    }

    public static void main(String[] args) throws InterruptedException {
        test_2();
    }

    /**
     * 当wait_1获取资源的时候，就会直接调用wait()方法进入暂停挂起的状态，线程休眠1s之后直接调用线程的notify()方法唤醒资源的某一个等待锁的线程
     * @throws InterruptedException
     */
    public static void test_1() throws InterruptedException {
        Thread wait1 = new Thread(new WaitDemo());
        wait1.setName("wait_1");
        wait1.start();
        Thread.sleep(1000L);
        synchronized (waitObject) {
            waitObject.notify();
        }
    }


    /**
     * 当wait_1获取资源的时候，就会直接调用wait()方法进入暂停挂起的状态，线程休眠1s之后直接调用线程的notify()方法唤醒某一个等待锁的线程
     * @throws InterruptedException
     */
    public static void test_2() throws InterruptedException {
        Thread wait1 = new Thread(new WaitDemo());
        wait1.setName("wait_1");
        wait1.start();

        Thread wait2 = new Thread(new WaitDemo());
        wait2.setName("wait_2");
        wait2.start();

        Thread wait3 = new Thread(new WaitDemo());
        wait3.setName("wait_3");
        wait3.start();


        Thread wait4 = new Thread(new WaitDemo());
        wait4.setName("wait_4");
        wait4.start();


        Thread wait5 = new Thread(new WaitDemo());
        wait5.setName("wait_5");
        wait5.start();

        Thread.sleep(5000L);


        synchronized (waitObject) {
            waitObject.notify();
        }
    }


    /**
     * 当wait_1获取资源的时候，就会直接调用wait()方法进入暂停挂起的状态，线程休眠1s之后直接调用线程的notify()方法唤醒某一个等待锁的线程
     * @throws InterruptedException
     */
    public static void test_3() throws InterruptedException {

    }
}
